package c6;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;

public class ProducerConsumerTest {
    private static final NoReentrantLock lock = new NoReentrantLock();
    private static final Condition notFull = lock.newCondition();
    private static final Condition notEmpty = lock.newCondition();
    private static final Queue<String> queue = new LinkedBlockingQueue<>();
    private static int queueSize = 10;

    public static void main(String[] args) {
        Thread producer = new Thread(new Runnable() {
            @Override
            public void run() {
                //取的独占锁
                lock.lock();
                try {
                    //如果队列满了则等待
                    while (queue.size() == queueSize) {
                        notEmpty.await();
                    }
                    //添加元素到队列
                    queue.add("ele");
                    System.out.println("队列增加一个");
                    //唤醒消费线程
                    notFull.signalAll();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });

        Thread consumer = new Thread(new Runnable() {
            @Override
            public void run() {
                //获取独占锁
                lock.lock();
                try {
                    //队列空则等待
                    while (0 == queue.size()) {
                        notFull.await();
                    }
                    //消费一个元素
                    String ele = queue.poll();
                    System.out.println("队列消费一个" + ele);
                    //唤醒生产线程
                    notEmpty.signalAll();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });

        producer.start();
        consumer.start();
    }

}
